/**
 * @Title: stationController.java
 * @Package tt.dz.mvc.controller.sys
 * @author pengyu
 * @date 2015年12月17日 上午10:21:55
 * @version V1.0
 */
package tt.dz.mvc.controller.sys;

import java.math.BigDecimal;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import tt.dz.dao.ext.charger.OmsChargerDao;
import tt.dz.dao.ext.charger.OmsChargerRateDao;
import tt.dz.dao.ext.charger.OmsChargerRateRepo;
import tt.dz.entity.base.JsonCommon;
import tt.dz.entity.base.JsonForList;
import tt.dz.entity.base.JsonPageForList;
import tt.dz.entity.charger.OmsCharger;
import tt.dz.entity.charger.OmsChargerRate;
import tt.dz.entity.charger.OmsChargerRateEntity;
import tt.dz.entity.charger.OmsChargerRateKey;
import tt.dz.entity.exception.BizException;
import tt.dz.mvc.controller.base.BaseAction;
import tt.dz.mvc.controller.base.BaseController;
import tt.dz.mvc.model.SaveRateModel;
import tt.dz.service.middleware.SetService;
import tt.dz.service.sys.OmsChargerRateService;
import tt.dz.tcp.socket.exception.CreateConnectionFailException;
import tt.dz.tcp.socket.exception.RetryFailException;
import tt.dz.util.ActionUtils;
import tt.dz.util.OmsConstant;
import tt.dz.util.SelectItemImpl;
import tt.dz.util.StringUtil;

@Controller
@RequestMapping("rateApi")
public class RateController extends BaseController
{
	@Resource
	OmsChargerRateService omsChargerRateService;
	//	@Resource
	//	OmsChargerDao omsChargerDao;
	//	@Resource
	//	OmsChargerRateDao omsChargerRateDao;
	@Autowired
	SetService setService;

	//	@RequestMapping("/getList")
	//	@ResponseBody
	//	public JsonForList getList(HttpServletRequest request, HttpServletResponse response) throws Exception {
	//		return omsChargerRateService.findList(obj, pageNo, pageSize, sortName, sortVal);
	//	}

	@RequestMapping(value = "findAllOrPage", method = RequestMethod.GET)
	@ResponseBody
	public JsonForList<?> findAllOrPage(HttpServletRequest request, HttpServletResponse response)
	{
		HttpSession session = request.getSession();
		String current_user_id = (String) session.getAttribute(BaseAction.CommonParam.SESSION_USERID);
		OmsChargerRate rate = genarateObj(request, current_user_id, false, true);
		return omsChargerRateService.findPageOrAll(ActionUtils.buildQueryParam(request, true), rate);
	}

	@RequestMapping(value = "findRate/{rateSchema}", method = RequestMethod.GET)
	@ResponseBody
	public JsonForList<?> findRate(@PathVariable(value = "rateSchema") String rateSchema, HttpServletRequest request, HttpServletResponse response)
	{
		return omsChargerRateService.findRate(rateSchema);
	}

	@RequestMapping(value = "findRateGroup", method = RequestMethod.GET)
	@ResponseBody
	public JsonPageForList findRateGroup(String rateSchema, HttpServletRequest request, HttpServletResponse response)
	{
		OmsChargerRate rate = new OmsChargerRate();
		if (StringUtil.isNumeric(rateSchema))
		{
			rate.setRate_schema(Integer.valueOf(rateSchema));
		}
		String fee_type = request.getParameter("fee_type");
		if (StringUtil.isNumeric(fee_type))
		{
			rate.setFee_type(Integer.valueOf(fee_type));
		}
		String default_for = request.getParameter("default_for");
		if (StringUtil.isNotBlank(default_for))
		{
			rate.setDefault_for(default_for);
		}
		String pageNo = request.getParameter("pageNo");
		String pageSize = request.getParameter("pageSize");
		String sortName = "serial_no";
		String sortVal = "1";//ASC
		String groupByStrs = "rate_schema";
		JsonPageForList  rateJsonPageForList = omsChargerRateService.findRateGroup(rate, StringUtil.isNumeric(pageNo) ? Integer.valueOf(pageNo) : null, StringUtil.isNumeric(pageSize) ? Integer.valueOf(pageSize) : null, sortName,
				StringUtil.isNumeric(sortVal) ? Integer.valueOf(sortVal) : null, groupByStrs,true);
		return rateJsonPageForList;
	}

	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public JsonCommon<?> add(HttpServletRequest request, HttpServletResponse response)
	{
		//		OmsChargerRate rate = genarateObj(request, getLoginUserId(request), true,false);
		String charge_mode = request.getParameter("charge_mode");
		OmsChargerRate qryChargerRate = new OmsChargerRate();
		//rate_name不能重复
		qryChargerRate.setRate_name(request.getParameter("rate_name"));
		qryChargerRate = omsChargerRateService.findOneExample(qryChargerRate, null, null);
		if (qryChargerRate != null)
		{
			return OmsConstant.jsonFail;
		}
		switch (charge_mode)
		{
			case "0":
				SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
				//			Time btime=new Time(sdf.parse(startTimeList.get(0)).getTime());
				//			BigDecimal bd=new BigDecimal(rateList.get(1));
				//			bd=bd.setScale(2, BigDecimal.ROUND_HALF_UP);
				String fee_type = request.getParameter("fee_type");
				List<String> serialNoList = JSON.parseArray(request.getParameter("serial_no"), String.class);
				List<String> startTimeList = JSON.parseArray(request.getParameter("start_time"), String.class);
				List<String> endTimeList = JSON.parseArray(request.getParameter("end_time"), String.class);
				List<String> rateList = JSON.parseArray(request.getParameter("rate"), String.class);
				String rate_name = request.getParameter("rate_name");
				List<OmsChargerRate> chargerRateList = new ArrayList<OmsChargerRate>();
				Date now = new Date();
				try
				{
					for (int i = 0; i < serialNoList.size(); i++)
					{
						OmsChargerRate chargerRate = new OmsChargerRate();
						chargerRate.setCharge_mode(Integer.valueOf(charge_mode));
						chargerRate.setFee_type(Integer.valueOf(fee_type));
						chargerRate.setSerial_no(Integer.valueOf(serialNoList.get(i)));
						chargerRate.setStart_time(new Time(sdf.parse(startTimeList.get(i)).getTime()));
						chargerRate.setEnd_time(new Time(sdf.parse(endTimeList.get(i)).getTime()));
						chargerRate.setRate(new BigDecimal(rateList.get(i)).setScale(2, BigDecimal.ROUND_HALF_UP));
						chargerRate.setSet_time(now);
						chargerRate.setValid_flag(1);
						chargerRate.setRate_name(rate_name);
						chargerRateList.add(chargerRate);
					}
				}
				catch (ParseException e)
				{
					e.printStackTrace();//TODO 新增错误代码描述
					return OmsConstant.jsonFail;
				}
				omsChargerRateService.saveList(chargerRateList);
				return OmsConstant.jsonSuccess;
			case "1":
				OmsChargerRate chargerRate = new OmsChargerRate();
				HttpSession session = request.getSession();
				String current_user_id = (String) session.getAttribute(BaseAction.CommonParam.SESSION_USERID);
				chargerRate = genarateObj(request, current_user_id, true, false);
				String rate = request.getParameter("rate");
				chargerRate.setRate(new BigDecimal(rate).setScale(2, BigDecimal.ROUND_HALF_UP));
				int result = omsChargerRateService.save(chargerRate);
				if (result <= 0)
				{
					return OmsConstant.jsonFail;
				}
				return OmsConstant.jsonSuccess;
			default:
				return OmsConstant.jsonFail;
		}
	}

	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public JsonCommon save(@Valid SaveRateModel model) throws BizException
	{
		omsChargerRateService.saveChargeRate(model);
		return new JsonCommon(OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public JsonCommon<?> update(HttpServletRequest request)
	{

		String rate_schema = request.getParameter("rate_schema");
		String rateName = request.getParameter("rate_name");
		String fee_type = request.getParameter("fee_type");
		String charge_mode = request.getParameter("charge_mode");
		//rateName不能重复
		OmsChargerRate qryChargerRate = new OmsChargerRate();
		qryChargerRate.setRate_name(rateName);
		qryChargerRate = omsChargerRateService.findOneExample(qryChargerRate, null, null);
		if (qryChargerRate != null)
		{
			return OmsConstant.jsonFail;
		}
		switch (charge_mode)
		{
			case "0":
				SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
				//			Time btime=new Time(sdf.parse(startTimeList.get(0)).getTime());
				//			BigDecimal bd=new BigDecimal(rateList.get(1));
				//			bd=bd.setScale(2, BigDecimal.ROUND_HALF_UP);
				List<String> serialNoList = JSON.parseArray(request.getParameter("serial_no"), String.class);
				List<String> startTimeList = JSON.parseArray(request.getParameter("start_time"), String.class);
				List<String> endTimeList = JSON.parseArray(request.getParameter("end_time"), String.class);
				List<String> rateList = JSON.parseArray(request.getParameter("rate"), String.class);
				List<OmsChargerRate> chargerRateList = new ArrayList<OmsChargerRate>();
				Date now = new Date();
				try
				{
					omsChargerRateService.deleteByRateSchema(rate_schema);
					for (int i = 0; i < serialNoList.size(); i++)
					{
						OmsChargerRate chargerRate = new OmsChargerRate();
						chargerRate.setCharge_mode(Integer.valueOf(charge_mode));
						chargerRate.setFee_type(Integer.valueOf(fee_type));
						chargerRate.setSerial_no(Integer.valueOf(serialNoList.get(i)));
						chargerRate.setStart_time(new Time(sdf.parse(startTimeList.get(i)).getTime()));
						chargerRate.setEnd_time(new Time(sdf.parse(endTimeList.get(i)).getTime()));
						chargerRate.setRate(new BigDecimal(rateList.get(i)).setScale(2, BigDecimal.ROUND_HALF_UP));
						chargerRate.setSet_time(now);
						chargerRate.setValid_flag(1);
						chargerRate.setRate_schema(Integer.valueOf(rate_schema));
						chargerRate.setRate_name(rateName);
						chargerRateList.add(chargerRate);
					}
				}
				catch (ParseException e)
				{
					e.printStackTrace();//TODO 新增错误代码描述
					return OmsConstant.jsonFail;
				}
				omsChargerRateService.saveList(chargerRateList);
				return OmsConstant.jsonSuccess;
			case "1":
				omsChargerRateService.deleteByRateSchema(rate_schema);
				OmsChargerRate chargerRate = new OmsChargerRate();
				HttpSession session = request.getSession();
				String current_user_id = (String) session.getAttribute(BaseAction.CommonParam.SESSION_USERID);
				chargerRate = genarateObj(request, current_user_id, true, false);
				String rate = request.getParameter("rate");
				chargerRate.setRate(new BigDecimal(rate).setScale(2, BigDecimal.ROUND_HALF_UP));
				int result = omsChargerRateService.save(chargerRate);
				if (result <= 0)
				{
					return OmsConstant.jsonFail;
				}
				return OmsConstant.jsonSuccess;
			default:
				return OmsConstant.jsonFail;
		}

	}

	@RequestMapping(value = "loginDelete", method = RequestMethod.POST)
	@ResponseBody
	public JsonCommon<?> loginDelete(HttpServletRequest request, HttpServletResponse response)
	{
		String rate_schema = request.getParameter("rate_schema");
		OmsChargerRate rate = new OmsChargerRate();
		rate.setRate_schema(Integer.valueOf(rate_schema));
		int result = omsChargerRateService.logicDelete(rate);
		if (result <= 0)
		{
			return OmsConstant.jsonFail;
		}
		return OmsConstant.jsonSuccess;
	}

	@RequestMapping(value = "bindChargers", method = RequestMethod.POST)
	@ResponseBody
	public JsonCommon<?> bindChargers(HttpServletRequest request, HttpServletResponse response)
	{
		String rate_schema = request.getParameter("rate_schema");
		String fee_type = request.getParameter("fee_type");
		//		String[] urlIds = request.getParameterValues("urlIds");
		String chargerIds_str = request.getParameter("chargerIds");
		List<String> chargerIdList = JSON.parseArray(chargerIds_str, String.class);
		OmsChargerRate rate = new OmsChargerRate();
		rate.setRate_schema(Integer.valueOf(rate_schema));
		int result = omsChargerRateService.bindChargers(rate_schema, Integer.valueOf(fee_type), chargerIdList);
		if (result <= 0)
		{
			return OmsConstant.jsonFail;
		}
		return OmsConstant.jsonSuccess;
	}

	@RequestMapping(value = "unBindChargers", method = RequestMethod.POST)
	@ResponseBody
	public JsonCommon<?> unBindChargers(HttpServletRequest request, HttpServletResponse response)
	{
		//		String rate_schema = request.getParameter("rate_schema");
		String fee_type = request.getParameter("fee_type");
		//		String[] urlIds = request.getParameterValues("urlIds");
		String chargerIds_str = request.getParameter("chargerIds");
		List<String> chargerIdList = JSON.parseArray(chargerIds_str, String.class);
		int result = omsChargerRateService.unBindChargers(Integer.valueOf(fee_type), chargerIdList);
		if (result <= 0)
		{
			return OmsConstant.jsonFail;
		}
		return OmsConstant.jsonSuccess;
	}

	//6.6.71.根据费率方案号查询电桩与费率绑定关系列表
	@RequestMapping(value = "findChargersBySchema", method = RequestMethod.GET)
	@ResponseBody
	public JsonForList<?> findChargersBySchema(HttpServletRequest request, HttpServletResponse response)
	{
		String rate_schema = request.getParameter("rate_schema");
		if (!StringUtil.isNumeric(rate_schema))
		{//MissParam("10303101", "缺少参数字段"),
			return new JsonForList<>(null, "10303101", "缺少参数字段");
		}
		//		OmsChargerRate chargerRate =  new OmsChargerRate();
		//		chargerRate.setRate_schema(Integer.valueOf(rate_schema));
		//		return omsChargerRateService.findChargersBySchema(rate_schema);
		List<OmsCharger> list = omsChargerRateService.findChargersBySchema(rate_schema);
		return new JsonForList<OmsCharger>(list, "200", "ok");
	}

	//6.6.72.查询未绑定某种费率的电桩列表
	@RequestMapping(value = "findNullChargers", method = RequestMethod.GET)
	@ResponseBody
	public JsonForList<?> findNullChargers(HttpServletRequest request, HttpServletResponse response)
	{
		String fee_type = request.getParameter("fee_type");
		String default_for = request.getParameter("default_for");  //default_for只有在不是默认费率时，才有值

		if (!StringUtil.isNumeric(fee_type))
		{//MissParam("10303101", "缺少参数字段"),
			return new JsonForList<>(null, "10303101", "缺少参数fee_type字段");
		}
		List<OmsCharger> list = omsChargerRateService.findNullChargers(fee_type,default_for);
		return new JsonForList<OmsCharger>(list, "200", "ok");
	}

	//根据电桩地址查询其对应的费率详情
	@RequestMapping(value = "findByChargerId", method = RequestMethod.GET)
	@ResponseBody
	public JsonForList<?> findByChargerId(HttpServletRequest request, HttpServletResponse response)
	{
		String charger_id = request.getParameter("charger_id");
		if (!StringUtil.isBlank(charger_id))
		{//MissParam("10303101", "缺少参数字段"),
			return new JsonForList<>(null, "10303101", "缺少参数字段");
		}
		List<OmsChargerRate> list = omsChargerRateService.findByChargerId(charger_id);
		return new JsonForList<OmsChargerRate>(list, "200", "ok");
	}

	private OmsChargerRate genarateObj(HttpServletRequest request, String userId, boolean isCreate, boolean isFind)
	{
		Map<String, String> params = ActionUtils.getParameterMap(request);
		return ActionUtils.getParamInstance(OmsChargerRate.class, params, userId, isCreate, isFind);
	}

	/**
	 * 下发费率方案到桩
	 * 使用场景:
	 * 1.1,1.2版本(电费费率方案+服务费费率方案),预留2.0版本(预约费费率方案+电费费率方案+服务费费率方案)
	 */
	@RequestMapping(value = "sendRatePlanToCharger")
	@ResponseBody
	public JsonCommon sendRatePlanToCharger(String chargerId) throws BizException, RetryFailException, CreateConnectionFailException
	{
		setService.sendFee(chargerId);
		return new JsonCommon(OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}

	public static void main(String[] args) throws ParseException
	{
		List<String> startTimeList = new ArrayList<String>();
		startTimeList.add("0:00");
		startTimeList.add("12:00");
		List<String> endTimeList = new ArrayList<String>();
		endTimeList.add("12:00");
		endTimeList.add("24:00");
		List<String> rateList = new ArrayList<String>();
		rateList.add("12.00");
		rateList.add("13.45");
		//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		Time btime = new Time(sdf.parse(startTimeList.get(0)).getTime());
		System.out.println(btime);

		String StrBd = "1048576.1024";

		BigDecimal bd = new BigDecimal(rateList.get(1));
		bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
		System.out.println(bd);
	}

}
